package com.kaifamiao.tcp;
import java.io.*;
import java.net.*;

public class FileSender {
    private final static int PORT = 7777;
    private final static int BUFFER_SIZE = 1024;
    private final static int MAX_RETRIES = 3;

    private final static String FILEPATH = "/Users/linrui/a/";
    public static void main(String[] args) {


        String receiverAddress = "127.0.0.1";

        for (int retries = 0; retries < MAX_RETRIES; retries++) {
            try (Socket socket = new Socket(receiverAddress, PORT);
                 OutputStream os = socket.getOutputStream();
                 ObjectOutputStream oos = new ObjectOutputStream(os)) {

                // 获取文件夹中的所有文件和子文件夹
                File folder = new File(FILEPATH);
                File[] listOfFiles = folder.listFiles();

                // 发送文件和子文件夹的数量
                oos.writeInt(listOfFiles.length);

                for (File file : listOfFiles) {
//                    System.out.println(file.getName());
                    sendFileOrFolder(file, oos);
                }

                System.out.println("文件及文件夹发送成功。");
                break; // 如果成功发送，跳出循环

            } catch (SocketException se) {
                System.out.println("连接出现问题，正在重试... (" + (retries + 1) + "/" + MAX_RETRIES + ")");
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }
    }

    // 递归发送文件或文件夹
    private static void sendFileOrFolder(File fileOrFolder, ObjectOutputStream oos) throws IOException {
        if (fileOrFolder.isDirectory()) {
            // 发送文件夹标识和名称
            oos.writeUTF("DIRECTORY");
            oos.writeUTF(fileOrFolder.getName());
            System.out.println("发送文件夹：->"+fileOrFolder.getName());
            // 递归发送文件夹内容
            File[] children = fileOrFolder.listFiles();
            oos.writeInt(children.length);
            for (File child : children) {
                sendFileOrFolder(child, oos);
            }
        } else {
            // 发送文件标识、名称和内容
            oos.writeUTF("FILE");
            oos.writeUTF(fileOrFolder.getName());
            oos.writeLong(fileOrFolder.length());
            System.out.println("发送文件：->"+fileOrFolder.getName());
            byte[] buffer = new byte[BUFFER_SIZE];
            try (FileInputStream fis = new FileInputStream(fileOrFolder)) {
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    oos.write(buffer, 0, bytesRead);
                }
            }
        }
    }
}
